package hibernate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.Session;
import java.util.List;
import java.util.Set;
import jaxb.AlbumContentMarshaller;
import jaxb.AlbumMarshaller;
import org.hibernate.Query;
import photogallery.Album;
import photogallery.Comment;
import photogallery.HibernateUtil;
import photogallery.Image;

/**
 *
 * @author ThuanPQ
 */
public class ImageDAO {

    private Session session;

    public ImageDAO() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    public Image insertImage(String albumId, String title, Date takenDate, String caption, String url, boolean isCover, String xmlFilePath) {
        try {
            session.getTransaction().begin();
            Integer abId = new Integer(albumId);
            AlbumDAO abDao = new AlbumDAO();
            Album album = abDao.findByAlbumID(abId);
            Image[] images = fromSetToArray(album);
            List coverIdList = new ArrayList<Integer>();
            if (isCover) {
                for (int j = 0; j < images.length; j++) {
                    if (images[j].isIsCover()) {
                        images[j].setIsCover(false);
                        coverIdList.add(images[j].getImageId());
                    }
                }
            } else {
                if (images.length == 0) {
                    isCover = true;
                }
            }

            Image img = new Image(album, title, takenDate, caption, url, isCover);
            session.save(img);            
            session.flush();
            session.getTransaction().commit();

            for (int j = 0; j < coverIdList.size(); j++) {
                Image image = findByImageID((Integer)coverIdList.get(j));
                image.setIsCover(false);
                session.getTransaction().begin();
                session.update(image);
                session.flush();
                session.getTransaction().commit();
            }

            if (isCover) {
                AlbumMarshaller am = new AlbumMarshaller();
                am.createXML(xmlFilePath);
            }
            AlbumContentMarshaller acm = new AlbumContentMarshaller();
            AlbumDAO anotherAbDao = new AlbumDAO();
            album = anotherAbDao.findByAlbumID(abId);
            acm.createXML(abId, fromSetToArray(album), xmlFilePath);
            return img;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    private Image[] fromSetToArray(Album album) {
        Image[] images = new Image[album.getImages().size()];
        Iterator<Image> it = album.getImages().iterator();
        int i = 0;
        while (it.hasNext()) {
            images[i] = it.next();
            i++;
        }
        return images;
    }

    public Image findByImageID(Integer imageID) {
        try {
            session.getTransaction().begin();

            String sql = "from Image where image_id=?";
            Query query = session.createQuery(sql);
            query.setString(0, String.valueOf(imageID));
            List resultList = query.list();

            Image[] images = new Image[resultList.size()];
            resultList.toArray(images);
            session.getTransaction().commit();
            return images[0];
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }

    public Image[] getAlbumImages(Integer albumId) {
        try {
            session.getTransaction().begin();
            String sql = "from Image where album_id=?";
            Query query = session.createQuery(sql);
            query.setString(0, String.valueOf(albumId));
            List resultList = query.list();
            Image[] images = new Image[resultList.size()];
            resultList.toArray(images);
            session.getTransaction().commit();
            return images;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Image[] getAllImages() {
        try {
            session.getTransaction().begin();
            String sql = "from Image";
            Query query = session.createQuery(sql);
            List resultList = query.list();
            Image[] images = new Image[resultList.size()];
            resultList.toArray(images);
            session.getTransaction().commit();
            return images;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
//    public void insertComment(Integer imageId, String author, Date createdDate, String content, String imageId) {
//        try {
//            session.getTransaction().begin();
//            Image img = (Image) session.get(Image.class, imageId);
//            Comment comment = new Comment(author, createdDate, content);
//            img.getComments().add(null);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public void deleteImage(Integer imageId) {
        try {
            session.getTransaction().begin();
            Image image = (Image) session.get(Image.class, imageId);
            session.delete(image);
            session.flush();
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
    }

}
